import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/model/car/car_cate_model.dart';
import 'package:flutter_yres/model/car/car_merchant_entity.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jlocation/jlocation.dart';
import 'package:flutter_yres/tool/star.dart';
import 'package:flutter_yres/pages/car/merchant_detail.dart';

class CarPage extends StatefulWidget {
  CarPage({Key key}) : super(key: key);

  @override
  _CarPageState createState() => _CarPageState();
}

class _CarPageState extends State<CarPage> {
  EasyRefreshController _controller = new EasyRefreshController();
  List<CarCateModelData> subs = []; //汽车顶级分类数组
  List<CarMerchantModelData> merchants = []; //商户列表
  double _listHeight = ScreenUtil.getInstance().setHeight(210); //单个列表高度
  int page = 1;
  var jyz_selectDistanceItemValue;
  var jyz_selectoilNoItemValue;
  var jyz_selectCondItemValue;
  var jyz_selectGasTypeItemValue;
  double lat, lng;
  @override
  Widget build(BuildContext context) {
    return  _buildSub();
    // Scaffold(
    //   appBar: AppBar(
    //     title: _buildSearch(),
    //     backgroundColor: Colors.white,
    //   ),
    //   body: _buildSub(),
    // );
  }

  //搜索组件
  _buildSearch() {
    return new Container(
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.all(0),
            child: FlatButton(
                onPressed: () {},
                child: Row(
                  children: <Widget>[
                    Image.asset('images/icon_nav_location.png'),
                    Text(
                      "定位",
                      style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(28)),
                    ),
                  ],
                )),
          ),
          Container(
            width: ScreenUtil.getInstance().setWidth(445),
            child: new MaterialButton(
              height: ScreenUtil.getInstance().setWidth(60),
              child: Row(
                children: <Widget>[
                  new Icon(Icons.search, color: Colors.grey),
                  new Text('搜索'),
                ],
              ),
              onPressed: () {},
              color: Color.fromRGBO(245, 245, 245, 1),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
            ),
          ),
          Container(
            margin: EdgeInsets.all(0),
            child: new IconButton(
              color: Colors.white,
              icon: Image.asset('images/icon_nav_order.png'),
              onPressed: () {
                // ...
              },
            ),
          )
        ],
      ),
      width: double.maxFinite,
      // height: kBottomNavigationBarHeight + 40,
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: Colors.white,
      // padding: EdgeInsets.fromLTRB(20, windowstateHeight, 20, 8),
    );
  }

  //其他类别主页内容
  Widget _buildSub() {
    return Container(
      child: new EasyRefresh(
        //刷新  加载组件
        controller: _controller,
        child: CustomScrollView(slivers: <Widget>[
          // SliverGrid(
          //   gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          //     maxCrossAxisExtent: (kScreenWidth - kMargin20) / 4,
          //     mainAxisSpacing: 10.0,
          //     crossAxisSpacing: 10.0,
          //     childAspectRatio: 1.15, //子控件宽高比
          //   ),
          //   delegate: SliverChildBuilderDelegate(
          //     (BuildContext context, int index) {
          //       return _itemBuilder(context, subs[index]);
          //     },
          //     childCount: subs.length,
          //   ),
          // ),
          SliverToBoxAdapter(
            child: Container(
                height: ScreenUtil.getInstance().setHeight(60),
                child: Column(
                  children: <Widget>[_buildPopHeader()],
                )),
          ),
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(_buildListItem,
                  childCount: merchants.length),
              itemExtent: _listHeight),
        ]),
        onRefresh: () async {},
        onLoad: () async {},
      ),
    );
  }

  _buildPopHeader() {
    //条件筛选头部
    var header = Container(
      height: ScreenUtil.getInstance().setHeight(40),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '全部',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectDistanceItemValue,
                    items: jyz_distanceItemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectDistanceItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '附近',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectoilNoItemValue,
                    items: jyz_oilNotemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectoilNoItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '智能排序',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectCondItemValue,
                    items: jyz_condtemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectCondItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '筛选',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectGasTypeItemValue,
                    items: jyz_gasTypetemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectGasTypeItemValue = T;
                        _refreshList();
                      });
                    },
                  ),
                ),
              ))
        ],
      ),
    );
    return header;
  }

  Widget _itemBuilder(BuildContext context, item) {
    return InkWell(
      onTap: () {

      },
      child: Column(
        children: <Widget>[
          Container(
            height: ScreenUtil.getInstance().setWidth(20),
          ),
          item.icon == ''
              ? Image(
                  image: AssetImage('images/pic_default.png'),
                  width: ScreenUtil.getInstance().setWidth(90))
              : Image.network(
                  Api.BaseUrl + item.icon,
                  width: ScreenUtil.getInstance().setWidth(90),
                ),
          Text(item.name)
        ],
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          CarMerchantModelData model = merchants[index];
           Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) =>
                    MerchantDetailPage(model: model,) //打开第二个页面，并传值，传递值的名称是model
                ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = Container(
      child: merchants[index].merchant_avatar == null
          ? Image.asset('images/pic_default.png')
          : new Image(
              image: NetworkImage(merchants[index].merchant_avatar),
              width: ScreenUtil.getInstance().setHeight(150),
              height: ScreenUtil.getInstance().setHeight(150),
              fit: BoxFit.fill),
      color: Colors.grey,
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      merchants[index].merchant_name,
      style: TextStyle(color: Colors.black, fontSize: 16.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var score = RichText(
      text: TextSpan(style: TextStyle(color: Colors.grey), children: [
        TextSpan(
            text: merchants[index].comment_score + '分',
            style: TextStyle(fontSize: 15.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: '¥' + merchants[index].consumption + '/人',
            style: TextStyle(color: Colors.grey)),
        TextSpan(text: '导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      // merchants[index].province +
      merchants[index].city +
          merchants[index].county +
          merchants[index].detail_address,
      style: TextStyle(color: Colors.grey, fontSize: 13.0),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 8, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(
                new StaticRatingBar(
                  size: 15.0,
                  rate: double.parse(merchants[index].comment_score),
                ),
                l: 8,
                t: 0,
                r: 0,
                b: 0),
            _pd(score, l: 8, t: 0, r: 8, b: 0),
            distance
          ],
        ),
        Row(
          children: <Widget>[
            _pd(
                Image.asset(
                  'images/icon_nav_location.png',
                  width: 13,
                  height: 15,
                  fit: BoxFit.fill,
                ),
                l: 0,
                t: 0,
                r: 0,
                b: 0),
            _pd(address, l: 10, t: 0, r: 10, b: 0),
          ],
        ),
        
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

//商户参数
  List<DropdownMenuItem> jyz_distanceItemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1000',
        child: new Text(
          '1千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '3000',
        child: new Text(
          '3千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '5000',
        child: new Text(
          '5千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '10000',
        child: new Text(
          '10千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_oilNotemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '92',
        child: new Text(
          '#92',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '95',
        child: new Text(
          '#95',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '98',
        child: new Text(
          '#98',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '0',
        child: new Text(
          '#0',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_condtemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '油价升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '距离升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    return items;
  }

  List<DropdownMenuItem> jyz_gasTypetemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '中石油',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '中石化',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '3',
        child: new Text(
          '壳牌',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '4',
        child: new Text(
          '其他',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  getLocation() {
    var loc = new Jlocation();
    loc.onLocationChanged().listen((loc) {
      setState(() {
        if (!mounted) return;
        lat = loc.latitude;
        lng = loc.longitude;
        _refreshList();
      });
    });
  }

  void _refreshList() {
    page = 1;
    getList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
  }

  getList(gasType, distinct, oilNo, cond) async {

    SharedPreferences preferences = await SharedPreferences.getInstance();
    //加油站
    FormData data;
    if (lat == null) {
      data = new FormData.fromMap({
        'distinct': 10,
        'page': page,
        'per': '8',
      });
    } else {
      data = new FormData.fromMap({
        'lng_lat': lng.toString() + "," + lat.toString(),
        'distinct': 10,
        'page': page,
        'per': '8',
      });
    }


    Response<String> response =
        await HttpUtil().post(Api.GetMerchantListUrl, data: data);
    Map userMap = json.decode(response.data);
    CarMerchantModelEntity jyzEntity =
        new CarMerchantModelEntity.fromJson(userMap);
    if (jyzEntity.code == 1) {

      if (mounted) {
        setState(() {
          if (page == 1) {
            merchants.clear();
            merchants = jyzEntity.data;
          } else {
            merchants.addAll(jyzEntity.data);
          }
        });
      }
    }
  }

  /*淘宝子级列表*/
  getCarTopCatList() async {
    FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.GetTopCatListUrl, data: data);
    Map userMap = json.decode(response.data);

    CarCateModelEntity itemEntity = new CarCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          subs.clear();
          subs = itemEntity.data;
        });
      }
    }
  }

  @override
  void initState() {

    _refreshList();
    getLocation();
    getCarTopCatList();
    super.initState();
  }
}
